<?php
function bpsc_admin_pages_on_load() {
	add_meta_box( 'bpsc-admin-metaboxes-settingsbox', __( 'Settings', 'bpsc' ), 'bpsc_admin_screen_settingsbox', 'store_page_wpsc-buddypress', 'normal', 'core' );
	add_meta_box( 'bpsc-admin-metaboxes-easycheckout-configurationbox', __( 'Easy Checkout Configuration', 'bpsc' ), 'bpsc_admin_screen_easycheckout_configurationbox', 'store_page_wpsc-buddypress', 'normal', 'core' );
}

/**
 * bpsc_admin_register_settings
 *
 * Required to utilise WordPress options API.
 */
function bpsc_admin_register_settings() {
	register_setting( 'bpsc-settings-group', 'bpsc', 'bpsc_admin_validate' );
}

/**
 * bpsc_admin_validate
 *
 * Validation function for register_setting.
 */
function bpsc_admin_validate( $new_settings ) {
	if ( is_string( $new_settings ) )  // wpmu-edit.php
		return get_blog_option( BP_ROOT_BLOG, 'bpsc' );

	if ( isset( $new_settings['easycheckouttoggle'] ) )
		$new_settings['easycheckouttoggle'] = ( $new_settings['easycheckouttoggle'] ) ? true : false;

	if ( isset( $new_settings['groupstoretoggle'] ) )
		$new_settings['groupstoretoggle'] = ( $new_settings['groupstoretoggle'] ) ? true : false;

	$temp = array();
	foreach ( $new_settings as $xprofile_field => $wpsc_value ) {
		if ( false === strpos( $xprofile_field, '||SPLIT||' ) )
			continue;

		$pieces = explode( '||SPLIT||', $xprofile_field, 2 );
		if ( 2 != count( $pieces ) )
			continue;

		if ( !isset( $temp[$pieces[0]] ) )
			$temp[$pieces[0]] = array();

		if ( $wpsc_value )
			$temp[$pieces[0]][$pieces[1]] = $wpsc_value;

		unset( $new_settings[$xprofile_field] );
	}
	$new_settings['easycheckout'] = $temp;

	foreach ( $new_settings['easycheckout'] as $group_name => $group_settings ) {
		foreach ( $group_settings as $setting ) {
			if ( !$setting )
				$setting = false;  // Was a string
			else
				$setting = apply_filters( 'bpsc_admin_validate_setting', $setting );
		}
	}

	return serialize( wp_parse_args( $new_settings, get_blog_option( BP_ROOT_BLOG, 'bpsc' ) ) );
}

// Add "Settings" link on plugins menu
function bpsc_admin_add_action_link( $links, $file ) {
	if ( 'bp-e-commerce/loader.php' != $file )
		return $links;

	$settings_link = '<a href="' . admin_url( 'admin.php?page=wpsc-buddypress' ) . '">' . __( 'Settings', 'bpsc' ) . '</a>';
	array_unshift( $links, $settings_link );

	return $links;
}
add_filter( 'plugin_action_links', 'bpsc_admin_add_action_link', 10, 2 );

/**
 * bpsc_admin()
 *
 * Admin page for the BuddyPress-specific settings.
 */
function bpsc_admin() {
	$settings = maybe_unserialize( get_blog_option( BP_ROOT_BLOG, 'bpsc' ) );
?>
	<div id="bp-admin">
	<div id="bpsc-admin-metaboxes-general" class="wrap">

		<div id="bp-admin-header">
			<h3><?php _e( 'BuddyPress', 'bpsc' ) ?></h3>
			<h4><?php _e( 'WP e-Commerce', 'bpsc' ) ?></h4>
		</div>

		<div id="bp-admin-nav">
			<ol>
				<li class="current"><?php _e( 'Easy Checkout <span class="ampersand">&amp;</span> Group Store', 'bpsc' ) ?></li>
			</ol>
		</div>

		<?php if ( isset( $_GET['updated'] ) ) : ?>
		<div id="message" class="updated">
			<p><?php _e( 'Your WP e-Commerce settings have been saved.', 'bpsc' ) ?></p>
		</div>
		<?php endif; ?>

		<form method="post" action="options.php" id="wpsc-buddypress">
			<?php wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false ) ?>
			<?php wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false ) ?>
			<?php settings_fields( 'bpsc-settings-group' ) ?>

			<div id="poststuff" class="metabox-holder">
				<div id="post-body" class="has-sidebar">
					<div id="post-body-content" class="has-sidebar-content">
						<?php do_meta_boxes( 'store_page_wpsc-buddypress', 'normal', $settings ) ?>
					</div>

					<p><input type="submit" class="button-primary" value="<?php _e( 'Save WP e-Commerce Settings', 'bpsc' ) ?>" /></p>
				</div>
			</div>

		</form>

	</div><!-- #bpsc-admin-metaboxes-general -->
	</div><!-- #bp-admin -->
<?php
}

function bpsc_admin_settings_toggle( $name, $settings ) {
	$checked = $settings["{$name}toggle"];
?>
	<input type="radio" class="<?php echo $name ?>" name="bpsc[<?php echo $name ?>toggle]" value="1" <?php if ( $checked ) echo 'checked="checked" ' ?>/> <?php _e( 'Enabled', 'bpsc' ) ?> &nbsp;
	<input type="radio" class="<?php echo $name ?>" name="bpsc[<?php echo $name ?>toggle]" value="0" <?php if ( !$checked ) echo 'checked="checked" ' ?>/> <?php _e( 'Disabled', 'bpsc' ) ?>
<?php
}

function bpsc_admin_screen_settingsbox( $settings ) {
?>
	<?php if ( bp_is_active( 'xprofile' ) ) : ?>
		<div class="component">
			<h5><?php _e( "Easy Checkout", 'bpsc' ) ?>
				<div class="radio">
					<?php bpsc_admin_settings_toggle( 'easycheckout', $settings ) ?>
				</div>
			</h5>

			<p><?php _e( "Tie together BuddyPress' xProfile fields with WP e-Commerce checkout fields, so that your users don't have to enter their details twice.", 'bpsc' ) ?></p>
		</div>
	<?php endif; ?>

	<?php if ( bp_is_active( 'groups' ) ) : ?>
		<div class="component">
			<h5><?php _e( "Group Store", 'bpsc' ) ?>
				<div class="radio">
					<?php bpsc_admin_settings_toggle( 'groupstore', $settings ) ?>
				</div>
			</h5>

			<p><?php _e( "Adds a store page to BuddyPress Groups.  Use this to let your Group Admins show categories of products that they think will interest their Group's members.", 'bpsc' ) ?></p>
		</div>
	<?php endif; ?>
<?php
}

function bpsc_admin_screen_easycheckout_configurationbox() {
	$settings = maybe_unserialize( get_blog_option( BP_ROOT_BLOG, 'bpsc' ) );

	if ( bp_is_active( 'xprofile' ) ) {
		$xprofile_options = array();
		$groups = BP_XProfile_Group::get( array( 'fetch_fields' => true ) );
		foreach ( $groups as $group ) {
			if ( !$group->fields )
				continue;

			$group_name = attribute_escape( $group->name );
			$xprofile_options[$group_name] = array();

			foreach ( $group->fields as $field )
				$xprofile_options[$group_name][] = new BP_XProfile_Field( $field->id );
		}
	}

	if ( bp_is_active( 'groups' ) ) {
		// todo2: this ought to be stored in wpsc/tikipress db
		$unique_names = array( 'billingfirstname', 'billinglastname', 'billingaddress', 'billingcity', 'billingcountry', 'billingemail', 'billingphone', 'billingpostcode', 'delivertoafriend', 'shippingfirstname', 'shippinglastname', 'shippingaddress', 'shippingcity', 'shippingstate', 'shippingcountry', 'shippingpostcode', 'tiki_firstname', 'tiki_lastname', 'tiki_email', 'tiki_twitter', 'tiki_blogurl', 'tiki_companyname', 'tiki_tshirtsize', 'tiki_mealrestrictions', 'tiki_wordpressuse', 'tiki_howmanyblogs', 'tiki_whichsessions', 'tiki_userdescription', 'tiki_commercial' );
		$unique_names_select_box = "<option value='0'>----</option>";
		foreach ( $unique_names as $name )
			$unique_names_select_box .= "<option value='" . esc_attr( $name ) . "'>" . $name . "</option>";
	}
?>
	<?php if ( bp_is_active( 'xprofile' ) ) : ?>
	<div class="setting-group setting-easycheckout <?php if ( !$settings["easycheckouttoggle"] ) echo 'initially-hidden' ?>">
		<div class="setting wide">
			<div class="settingname">
				<p><?php _e( "Associate a BuddyPress xProfile field with a row on the checkout form. This will automatically populate the form fields on the checkout screen with the details from the user's BuddyPress profile.", 'bpsc' ) ?></p>
			</div>
			<div class="settingvalue">

			<?php foreach ( $xprofile_options as $group_name => $field_objs ) : ?>
				<h4><?php echo $group_name ?></h4>

				<div>
					<?php foreach ( $field_objs as $field ) : $selected = ''; ?>
					<p><?php echo $field->name ?></p>
					<select name="bpsc[<?php echo esc_attr( $group_name. '||SPLIT||' . $field->id ) ?>]">
						<option value="0">----</option>
						<?php foreach ( $unique_names as $name ) : ?>

							<?php if ( !$selected && $settings['easycheckout'] && $name == esc_attr( $settings['easycheckout'][$group_name][$field->id] ) ) { $selected = ' selected'; } else { $selected = ''; } ?>
							<option value="<?php echo esc_attr( $name ) ?>"<?php echo $selected ?>><?php echo $name ?></option>
						<?php endforeach; ?>
					</select>

					<?php endforeach; ?>
				</div>
			<?php endforeach; ?>

			</div>
			<div style="clear: left"></div>
		</div>
	</div>
	<?php endif; ?>
<?php
}
?>